<template>
  <div>
    <div class="navbar">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <router-link to="/dashboard/dash" class="nav-link">首页</router-link>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <router-link :to="{ 
            name: 'Dashboard',
            params: { 
              standardName: standardName 
            }
          }" class="nav-link">
            <span>{{ standardName || '标准管理' }}</span>
          </router-link>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <router-link :to="{ 
            name: 'project-manage',
            params: { 
              param: projectId,
              standardName: standardName
            }
          }" class="nav-link">
            <span>{{ projectName || '项目管理' }}</span>
          </router-link>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <router-link :to="{ 
            name: 'people',
            params: { 
              param: projectId,
              standardName: standardName,
              projectName: projectName
            }
          }" class="nav-link">人员管理</router-link>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="current-page">授权列表</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="audit-list">
      <el-row class="filter-section">
        <el-col :span="8">
          <el-input
            v-model="searchText"
            placeholder="请输入搜索关键字"
            prefix-icon="el-icon-search"
          ></el-input>
        </el-col>
        <el-col :span="16">
          <el-button type="primary" @click="searchRecords">查询</el-button>
          <el-button type="success" @click="exportToExcel">导出Excel</el-button>
        </el-col>
      </el-row>

      <el-table
        :data="pagedData"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="sId" label="序号" width="100"></el-table-column>
        <el-table-column prop="uName" label="培训人员" width="180"></el-table-column>
        <el-table-column prop="startTime" label="培训日期" width="180"></el-table-column>
        <el-table-column prop="sRead" label="结束日期" width="180"></el-table-column>
        <el-table-column prop="pass" label="审核状态" width="180">
          <template #default="scope">
            <el-tag :type="scope.row.pass === 1 ? 'success' : 'danger'">
              {{ scope.row.pass === 1 ? '已通过' : (scope.row.pass === 2 ? '已驳回' : '未通过') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="text" size="small" @click="viewDetails(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      projectId: null,
      standardName: '',
      projectName: '',
      staId: null,
      searchText: '',
      tableData: [],
      filteredData: [],
      pagedData: [],
      currentPage: 1,
      pageSize: 10,
      editDialogVisible: false,
      editForm: {
        sId: '',
        uName: '',
        startTime: '',
        sRead: '',
        pass: 0
      },
      formLabelWidth: '120px'
    };
  },
  created() {
    const { param, projectName, standardName, staId } = this.$route.params;
    
    this.projectId = param;
    this.projectName = projectName;
    this.standardName = standardName;
    this.staId = staId;

    if (!param || !projectName || !standardName) {
      const savedParams = JSON.parse(localStorage.getItem('auditListParams') || '{}');
      
      this.projectId = savedParams.projectId || param;
      this.projectName = savedParams.projectName || projectName || '未知项目';
      this.standardName = savedParams.standardName || standardName || '未知标准';
      this.staId = savedParams.staId || staId;
    }

    localStorage.setItem('auditListParams', JSON.stringify({
      projectId: this.projectId,
      projectName: this.projectName,
      standardName: this.standardName,
      staId: this.staId
    }));

    if (!this.projectName || !this.standardName) {
      this.fetchProjectInfo();
    }

    this.fetchStudyRecords();
  },
  methods: {
    async fetchProjectInfo() {
      try {
        const response = await this.$http.get('/project/getProjectInfo', {
          params: { projectId: this.projectId }
        });

        if (response.data) {
          this.projectName = response.data.pjName || this.projectName;
          this.standardName = response.data.staName || this.standardName;

          const savedParams = JSON.parse(localStorage.getItem('auditListParams') || '{}');
          savedParams.projectName = this.projectName;
          savedParams.standardName = this.standardName;
          localStorage.setItem('auditListParams', JSON.stringify(savedParams));
        }
      } catch (error) {
        console.error('获取项目信息失败:', error);
      }
    },
    handleBack() {
      this.$router.push({
        name: 'people',
        params: { 
          param: this.projectId,
          standardName: this.standardName,
          projectName: this.projectName,
          staId: this.staId
        }
      });
    },
    getProjectId() {
      return this.projectId || 
             this.$route.params.param || 
             JSON.parse(localStorage.getItem('auditListParams') || '{}').projectId;
    },
    async fetchStudyRecords() {
      const projectId = this.getProjectId();
      
      if (!projectId) {
        this.$message.error('项目 ID 缺失，无法获取学习记录');
        return;
      }

      try {
        const response = await this.$http.get('/training/getStudyRecords', {
          params: { projectId }
        });
        
        console.log('后端返回的数据:', response.data);
        this.tableData = response.data;
        this.filteredData = this.tableData;
        this.updatePagedData();
      } catch (error) {
        this.$message.error('获取学习记录失败');
        console.error(error);
      }
    },
    searchRecords() {
      if (this.searchText.trim() === '') {
        this.filteredData = this.tableData;
      } else {
        const keyword = this.searchText.trim();
        this.filteredData = this.tableData.filter(record =>
          Object.values(record).some(
            value =>
              String(value)
                .toLowerCase()
                .includes(keyword.toLowerCase())
          )
        );
      }
      this.currentPage = 1;
      this.updatePagedData();
    },
    async exportToExcel() {
      try {
        const projectId = this.getProjectId();
        if (!projectId) {
          this.$message.error('项目 ID 缺失，无法导出');
          return;
        }

        const url = 'http://localhost:8081/training/exportStudyRecords';
        
        const response = await axios.get(url, {
          params: { projectId },
          responseType: 'blob',
        });

        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });

        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        
        const contentDisposition = response.headers['content-disposition'];
        let fileName = 'study_records.xlsx';
        if (contentDisposition) {
          const fileNameMatch = contentDisposition.match(/filename="?(.+)"?/);
          if (fileNameMatch && fileNameMatch.length === 2) {
            fileName = fileNameMatch[1];
          }
        }

        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        link.remove();
      } catch (error) {
        this.$message.error('导出失败');
        console.error(error);
      }
    },
    viewDetails(row) {
      const projectId = this.getProjectId();
      const params = {
        projectId: projectId,
        standardName: this.standardName || localStorage.getItem('standardName'),
        projectName: this.projectName || localStorage.getItem('projectName'),
        staId: this.staId || localStorage.getItem('staId')
      };

      this.$router.push({
        name: 'audit',
        params,
        query: {
          id: row.sId,
          pass: row.pass,
          uId: row.uId
        }
      });
    },
    handleEdit(row) {
      this.editForm = { ...row };
      this.editDialogVisible = true;
    },
    
    handlePageChange(newPage) {
      this.currentPage = newPage;
      this.updatePagedData();
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      this.updatePagedData();
    },
    updatePagedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.pagedData = this.filteredData.slice(start, end);
    }
  },
  watch: {
    tableData() {
      this.filteredData = this.tableData;
      this.updatePagedData();
    }
  }
};
</script>

<style scoped>
.navbar {
  padding: 20px;
  background-color: #f5f7fa;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  margin-bottom: 20px;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nav-back {
  margin-left: auto;
}

.nav-back .el-button {
  font-size: 14px;
  color: #909399;
}

.nav-back i {
  margin-right: 5px;
}

.el-breadcrumb {
  font-size: 16px;
  line-height: 1.5;
}

.el-breadcrumb ::v-deep .el-breadcrumb__inner a {
  color: #909399;  /* 非当前页面使用灰色 */
  font-weight: 400;
  font-size: 16px;
}

.current-page {
  color: #409EFF !important;  /* 当前页面使用蓝色 */
  font-weight: 500;
  font-size: 16px;
}

.audit-list {
  padding: 20px;
}
.filter-section {
  margin-bottom: 20px;
}
</style>